// 简单的 JS bridge 封装
window.MiniApp = (function(){
const callbacks = {}


function genId() {
return 'id-' + Math.random().toString(36).slice(2) + Date.now()
}


// 接收来自 Native 的回调（通过 window.dispatchEvent(new MessageEvent('message', ...)))）
window.addEventListener('message', (ev) => {
const msg = ev.data
if (!msg || !msg.id) return
const cb = callbacks[msg.id]
if (!cb) return
if (msg.status === 0) cb.resolve(msg.result)
else cb.reject(msg.error || { code: msg.status })
delete callbacks[msg.id]
})


function post(payload) {
const json = JSON.stringify(payload)
// Android: __nativeBridge.postMessage(json)
if (window.__nativeBridge && window.__nativeBridge.postMessage) {
try { window.__nativeBridge.postMessage(json); return }
catch(e) { console.error(e) }
}
// iOS WKWebView: window.webkit.messageHandlers.__nativeBridge.postMessage
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.__nativeBridge) {
try { window.webkit.messageHandlers.__nativeBridge.postMessage(json); return }
catch(e) { console.error(e) }
}
console.warn('no native bridge available')
}


return {
call(method, params){
const id = genId()
const payload = { id, method, params }
return new Promise((resolve, reject) => {
callbacks[id] = { resolve, reject }
post(payload)
// 超时保护
setTimeout(() => {
if (callbacks[id]) {
reject({ code: 'TIMEOUT' })
delete callbacks[id]
}
}, 15000)
})
}
}
})()